package com.googlecode.scenemaker3d.view.timeline
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.core.Application;

	public class SnapDraggableObj extends Sprite
	{
		protected var objIsDragging:Sprite = null;
		protected var objWidth:uint;
		protected var objOffset:Number;
		
		private var hArea:Sprite;
		private var eDragging:Boolean = true;
		private var lastPos:uint;
		
		public function SnapDraggableObj(w:uint)
		{
			super();
			
			objWidth = w;
			hArea = getHitArea();
			
			Application.application.addEventListener(MouseEvent.MOUSE_UP, onStageUp);
			Application.application.addEventListener(MouseEvent.MOUSE_MOVE, onStageMove);
			Application.application.addEventListener(MouseEvent.ROLL_OUT, onStageOut);
			
			this.addEventListener(MouseEvent.MOUSE_DOWN, onObjDown);
		}
		private function onStageUp(e:MouseEvent):void
		{
			if(objIsDragging)
			{
				objIsDragging = null;
				
				this.removeChild(hArea);
				this.dispatchEvent(new Event("objectUp"));
			}	
		}
		private function onStageOut(e:MouseEvent):void
		{
			if(objIsDragging)
			{
				objIsDragging = null;
				this.removeChild(hArea);
				this.dispatchEvent(new Event("objectUp"));
			}
		}
		protected function onStageMove(e:MouseEvent):void
		{
			if(objIsDragging && this.enableDragging == true)
			{
				this.x = Math.round((this.parent.mouseX - objOffset) / objWidth) * objWidth;
				//Prevent less than 0		
				if(this.x < 0)
				{
					this.x = 0;
				}
				if(this.x != lastPos)
				{
					this.dispatchEvent(new Event("objectMove"));
				}
					
				lastPos = this.x;
			}
		}
		private function onObjDown(e:MouseEvent):void
		{
			objOffset = e.localX;
			this.addChild(hArea);
			objIsDragging = (e.currentTarget as Sprite);
		}
		private function getHitArea():Sprite
		{
			var hArea:Sprite = new Sprite();
			hArea.name = "hArea";
			
			hArea.graphics.beginFill(0x000000, 0);
			hArea.graphics.drawRect(-200, -200, 400, 400);
			
			return hArea;
		}
		/* protected function update():void
		{
			this.dispatchEvent(new Event("objectMove"));
		} */
		public function set time(t:Number):void
		{
			this.x = Math.round(t / objWidth) * objWidth;
			//Prevent less than 0		
			if(this.x < 0)
			{
				this.x = 0;
			}
			
		}
		public function get time():Number
		{
			return this.x;
		}
		public function set enableDragging(enable:Boolean):void
		{
			eDragging = enable;
		}
		public function get enableDragging():Boolean
		{
			return eDragging;
		}
	}
}